from cryptography.fernet import Fernet, InvalidToken
from ..config import get_settings


def _get_fernet() -> Fernet:
    settings = get_settings()
    key = settings.secret_key
    # Accept both a ready-made Fernet key or a raw 32-byte base64 key string
    try:
        return Fernet(key)
    except Exception as exc:  # noqa: BLE001
        raise RuntimeError(
            "Invalid secret_key for Fernet. Generate one via: from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
        ) from exc


def encrypt_text(plaintext: str) -> str:
    """Encrypt plaintext with Fernet.

    如果没有配置有效的 SECRET_KEY，则退化为明文存储（不加密）。
    """
    if plaintext is None:
        return ""
    try:
        f = _get_fernet()
        token = f.encrypt(plaintext.encode("utf-8"))
        return token.decode("utf-8")
    except Exception:
        # No encryption fallback
        return plaintext


def decrypt_text(token_text: str) -> str:
    """Decrypt token.

    如果没有配置有效的 SECRET_KEY，则按明文回传（不解密）。
    """
    if not token_text:
        return ""
    try:
        f = _get_fernet()
        return f.decrypt(token_text.encode("utf-8")).decode("utf-8")
    except Exception:
        # No encryption fallback
        return token_text

